package top.songxs.gmall.order.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.songxs.gmall.order.biz.OrderBizService;
import top.songxs.gmall.rabbit.constant.MqConstant;
import top.songxs.gmall.rabbit.service.RabbitMqBizService;

import java.io.IOException;
import java.util.Map;

@Component
public class UpdateOrderStatus {

    @Autowired
    private RabbitMqBizService rabbitMqBizService;
    @Autowired
    private OrderBizService orderBizService;

    //订单支付完成后修改订单状态为已支付
    @RabbitListener(queues = {MqConstant.PAYED_QUEUE})
    public void payed(Message message, Channel channel) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        byte[] body = message.getBody();
        try {
            //调用业务成方法进行业务执行
            Map<String, String> params = JSON.parseObject(new String(body), Map.class);

            //调用业务成方法进行业务执行
            orderBizService.payedUpdateOrderStatus(params);
            //2、保存支付数据到支付表中【payment_info】

            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            rabbitMqBizService.retry(message, channel, 3);  //失败重试三次
            throw new RuntimeException(e);
        }
    }
/**    库存系统扣减库存完成之后，这边修改订单状态为代发货状态
    public void sendSkuDeductMQ(WareOrderTask wareOrderTask) {
    Map<String, Object> map = new HashMap<>();
    map.put("orderId", wareOrderTask.getOrderId());
     map.put("status", wareOrderTask.getTaskStatus().toString());
    this.sendMessage(MqConst.EXCHANGE_DIRECT_WARE_ORDER, MqConst.ROUTING_WARE_ORDER, JSON.toJSONString(map));
    }*/
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(MqConstant.QUEUE_WARE_ORDER),
            exchange = @Exchange(MqConstant.EXCHANGE_DIRECT_WARE_ORDER),
            key = MqConstant.ROUTING_WARE_ORDER
    ))
    public void waitingShipment(Message message, Channel channel) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        byte[] body = message.getBody();
        String msg = new String(body);
        Map<String,String> map = JSON.parseObject(msg, Map.class);
        try {
            orderBizService.updateOrderStatusToWaitingShipment(map);
            channel.basicAck(deliveryTag,true);
        } catch (IOException e) {
            rabbitMqBizService.retry(message,channel,3);
            throw new RuntimeException(e);
        }


    }
}
